package com.ricervcvcer.category.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ricervcvcer.category.entity.TbCategory;
import com.ricervcvcer.category.mapper.TbCategoryMapper;
import com.ricervcvcer.category.service.ITbCategoryService;
import com.ricervcvcer.category.vo.CategoryVO;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 商品类目表，类目和商品(spu)是一对多关系，类目与品牌是多对多关系 服务实现类
 * </p>
 *
 * @author moge
 * @since 2022-01-05
 */
@Service
public class TbCategoryServiceImpl extends ServiceImpl<TbCategoryMapper, TbCategory> implements ITbCategoryService {

    @Resource
    private TbCategoryMapper categoryMapper;

    @Override
    public List<Long> selectBrandIdsByCategoryId(Long categoryId) {
        return categoryMapper.selectBrandIdsByCategoryId(categoryId);
    }

    @Override
    public List<CategoryVO> brands() {
        // 查询一级分类
        QueryWrapper qw=new QueryWrapper();
        qw.eq("parent_id",0);
        List<CategoryVO> list = convent(qw);

        list.forEach(item->{
            // 查询一级分类下的二级分类
            QueryWrapper qw2=new QueryWrapper();
            qw2.eq("parent_id",item.getId());
            List<CategoryVO> list1 =convent(qw2);
            list1.forEach(item2->{
                // 查询一级分类下的二级分类
                QueryWrapper qw3=new QueryWrapper();
                qw3.eq("parent_id",item2.getId());
                List<CategoryVO> list2 = convent(qw3);
                item2.setCategoryVOList(list2);
            });
            item.setCategoryVOList(list1);
        });
        return list;
    }

    public List<CategoryVO> convent(QueryWrapper qw){
        List<TbCategory> list = categoryMapper.selectList(qw);
         List<CategoryVO> collect = list.stream().map(item -> {
            CategoryVO categoryVO = new CategoryVO();
            BeanUtils.copyProperties(item, categoryVO);
            return categoryVO;
        }).collect(Collectors.toList());
         return collect;
    }
}
